package com.pangcq.middleware.server.service.redis;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.pangcq.middleware.model.entity.Item;
import com.pangcq.middleware.model.mapper.ItemMapper;
import org.assertj.core.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@SuppressWarnings("all")
@Service
public class CachePassService {

    private static final Logger log = LoggerFactory.getLogger(CachePassService.class);

    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ObjectMapper objectMapper;

    private static final String keyPrefix = "item:";

    public Item getItemInfo(String itemCode) throws IOException {
        Item item = null;
        // 定义缓存中真正的key
        final String key = keyPrefix + itemCode;
        ValueOperations valueOperations = redisTemplate.opsForValue();
        if (redisTemplate.hasKey(key)) {
            log.info("从缓存中获取商品");
            Object o = valueOperations.get(key);
            if (o != null && !Strings.isNullOrEmpty(o.toString())) {
                item = objectMapper.readValue(o.toString(), Item.class);
            }
        } else {
            log.info("从数据库中获取商品");
            item = itemMapper.selectByCode(itemCode);
            if (item != null) {
                valueOperations.set(key, objectMapper.writeValueAsString(item));
            } else {
                // 过期失效时间TTL设置为30分钟，实际情况要根据实际业务决定
                valueOperations.set(key, "", 30L, TimeUnit.MINUTES);
            }
        }
        return item;
    }

}
